package com.furnitur.modules.admin.service.product.impl;

import com.furnitur.core.entity.product.Furniture;
import com.furnitur.core.mapper.product.FurnitureMapper;
import com.furnitur.modules.admin.dto.product.FurnitureQueryDTO;
import com.furnitur.modules.admin.service.product.FurnitureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import org.springframework.beans.BeanUtils;
import com.furnitur.modules.admin.dto.product.FurnitureDTO;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.entity.user.Merchant;
import com.furnitur.core.service.UserService;
import com.furnitur.core.mapper.user.MerchantMapper;
import org.springframework.transaction.annotation.Transactional;
import com.furnitur.core.entity.product.FurnitureCategory;
import com.furnitur.core.mapper.product.FurnitureCategoryMapper;
import com.furnitur.common.service.DataPermissionService;

@Service
@Slf4j
public class FurnitureServiceImpl implements FurnitureService {
    @Autowired
    private FurnitureMapper furnitureMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private FurnitureCategoryMapper categoryMapper;

    @Autowired
    private DataPermissionService dataPermissionService;

    @Override
    public IPage<Furniture> list(FurnitureQueryDTO queryDTO) {
        // 获取当前商家ID
        Long merchantId = dataPermissionService.getCurrentMerchantId();
        
        // 构建查询条件
        QueryWrapper<Furniture> wrapper = new QueryWrapper<>();
        // 强制加入商家ID条件
        wrapper.eq("merchant_id", merchantId);
        
        // 添加查询条件
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            wrapper.like("name", queryDTO.getKeyword())
                    .or()
                    .like("description", queryDTO.getKeyword());
        }
        
        if (queryDTO.getCategoryId() != null) {
            wrapper.eq("category_id", queryDTO.getCategoryId());
        }
        
        if (queryDTO.getStatus() != null) {
            wrapper.eq("status", queryDTO.getStatus());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge("created_at", queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le("created_at", queryDTO.getEndTime());
        }
        
        // 按创建时间倒序
        wrapper.orderByDesc("created_at");
        
        // 获取分页数据
        IPage<Furniture> furniturePage = furnitureMapper.selectPage(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), wrapper);
        
        // 填充分类名称
        for (Furniture furniture : furniturePage.getRecords()) {
            if (furniture.getCategoryId() != null) {
                FurnitureCategory category = categoryMapper.selectById(furniture.getCategoryId());
                if (category != null) {
                    furniture.setCategoryName(category.getName());
                }
            }
        }
        
        return furniturePage;
    }

    @Override
    public Furniture getById(Long id) {
        return furnitureMapper.selectById(id);
    }

    @Override
    @Transactional
    public void create(FurnitureDTO furnitureDTO) {
        // 获取当前登录的商家用户
        User currentUser = userService.getCurrentUser();
        log.info("Creating furniture for user: {}", currentUser);

        // 获取商家信息
        Merchant merchant = merchantMapper.selectOne(
            new QueryWrapper<Merchant>()
                .eq("user_id", currentUser.getId())
        );
        
        if (merchant == null) {
            log.error("Merchant not found for user: {}", currentUser.getId());
            throw new RuntimeException("商家信息不存在");
        }
        
        log.info("Found merchant: {}", merchant);

        // 创建商品实体
        Furniture furniture = new Furniture();
        furniture.setMerchantId(merchant.getId()); // 设置商家ID
        furniture.setCategoryId(furnitureDTO.getCategoryId());
        furniture.setName(furnitureDTO.getName());
        furniture.setDescription(furnitureDTO.getDescription());
        furniture.setPrice(furnitureDTO.getPrice());
        furniture.setStock(furnitureDTO.getStock());
        furniture.setImageUrl(furnitureDTO.getImageUrl());
        furniture.setStatus(furnitureDTO.getStatus());
        
        log.info("Inserting furniture: {}", furniture);
        
        try {
            furnitureMapper.insert(furniture);
        } catch (Exception e) {
            log.error("Error creating furniture", e);
            throw new RuntimeException("创建商品失败: " + e.getMessage());
        }
    }

    @Override
    public void update(Long id, FurnitureDTO furnitureDTO) {
        Furniture furniture = furnitureMapper.selectById(id);
        if (furniture == null) {
            throw new RuntimeException("商品不存在");
        }
        BeanUtils.copyProperties(furnitureDTO, furniture);
        furnitureMapper.updateById(furniture);
    }

    @Override
    public void delete(Long id) {
        furnitureMapper.deleteById(id);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Furniture furniture = new Furniture();
        furniture.setId(id);
        furniture.setStatus(status);
        furnitureMapper.updateById(furniture);
    }

    // ... 其他方法实现
} 